package cn.jinbyte.web.resolver;


import cn.jinbyte.core.handler.crypt.CryptHandler;
import cn.jinbyte.core.helper.SpringContextHelper;
import cn.jinbyte.web.annotation.CryptProp;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Objects;

/**
 * 密文参数解析器
 *
 * @author jinty
 * @since 1.0.0
 */
@Slf4j
public class CryptPropArgResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(@NonNull MethodParameter parameter) {
        CryptProp cryptPropArg = parameter.getParameterAnnotation(CryptProp.class);
        return cryptPropArg != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        // 从请求中解析参数值
        String parameterValue = webRequest.getParameter(Objects.requireNonNull(parameter.getParameterName()));
        if (parameterValue == null) {
            return null;
        }
        CryptProp cryptPropArg = parameter.getParameterAnnotation(CryptProp.class);
        if (cryptPropArg == null) {
            return parameterValue;
        }
        Class<? extends CryptHandler> handlerClass = cryptPropArg.handler();
        CryptHandler cryptHandler = SpringContextHelper.getBean(handlerClass);
        Class<?> parameterType = parameter.getParameterType();
        return cryptHandler.decode(parameterValue, parameterType);
    }
}
